/**
 * Created by wei on 17/11/23.
 */


import React, { Component } from 'react';
import axios from 'axios';
import base from '../base.js';
import cookie from '../cookie.js';
import PropTypes from 'prop-types';
import "./css/publish.css";

const basePath = base().basePath;

class RegisterForm extends Component{
    constructor(props){
        super(props);
        this.state = {
            errorInfo:'',
            loading:false
        }
        this.handleSubmit = this.handleSubmit.bind(this);
        this.validateEmail = this.validateEmail.bind(this);
        this.validate = this.validate.bind(this);
        this.validatePassword = this.validatePassword.bind(this);
        this.validateNickname = this.validateNickname.bind(this);
        this.strlen = this.strlen.bind(this);
    }

    hideDiv(){
        this.setState({
            loading:false,
        });
        const {fnHideDiv} = this.props;
        fnHideDiv();
    }


    handleSubmit(){
        this.setState({
            loading:true,
        });
        var that = this;
        if(this.validate()){
            axios.post(basePath+'/user/register',{'username':this.refs.username.value,
                'password':this.refs.password.value,
                'nickname':this.refs.nickname.value})
                .then((res) => {
                    if(res.data.token){

                        var token = res.data.token;
                        var nickname = res.data.nickname;
                        var avatar = res.data.avatar;
                        cookie.setCookie('nickname',nickname,100);
                        cookie.setCookie('token',token,100);
                        cookie.setCookie('avatar',avatar,100);
                        const {fnHideDiv} = that.props;
                        setTimeout(function () {
                            that.setState({
                                loading:false,
                            });
                            fnHideDiv();
                        }, 1500);
                    }
                });
        }else{
            this.setState({
                loading:false,
            });
        }
        return false;
    }



    strlen(str){
        var len = 0;
        for (var i = 0; i < str.length; i++) {
            var c = str.charCodeAt(i);
            //单字节加1
            if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
                len++;
            }
            else {
                len += 2;
            }
        }
        return len;
    }

    validateEmail(e){
        // const value = e.target.value;
        const value = this.refs.username.value;
        this.setState({
            errorInfo:''
        });
        if(value.length === 0){
            this.setState({
                errorInfo:'请填写邮箱帐号.'
            });
            return false;
        }else{
            const emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            if(!emailRegex.test(value)){
                this.setState({
                    errorInfo:'帐号需要为邮箱.'
                });
                return false;
            }
            axios.post(basePath+'/user/check/username',{'username':this.refs.username.value})
                .then((res) => {
                    if(res.data.result){
                        this.setState({
                            errorInfo:'邮箱已存在.'
                        });
                        return false;
                    }
                });
        }
        return true;
    }

    validate(e){
        if(!this.validateEmail()){
            return false;
        }
        if(!this.validatePassword()){
            return false;
        }
        if(!this.validateNickname()){
            return false;
        }

        return true;
    }


    validatePassword(e){
        const value = this.refs.password.value;
        this.setState({
            errorInfo:''
        });
        if(value.length < 4 || value.length > 32){
            this.setState({
                errorInfo:'请填写密码(4-32位).'
            });
            return false;
        }
        return true;

    }

    validateNickname(e){

        const value = this.refs.nickname.value;
        // console.log(value +" length is"+ this.strlen(value));
        this.setState({
            errorInfo:''
        });
        var vLength = this.strlen(value);
        if(vLength < 1 || vLength > 14){
            this.setState({
                errorInfo:'请填写昵称(英文1-14位,中文1-7位).'
            });
            return false;
        }

        axios.post(basePath+'/user/check/nickname',{'nickname':this.refs.nickname.value})
            .then((res) => {
                if(res.data.result){
                    this.setState({
                        errorInfo:'昵称已存在.'
                    });
                    return false;
                }
            });

        return true;
    }



    showLoading(){
        if(this.state.loading){
            return (
                <div style={{position:'absolute', top:'130px', left:'190px', zIndex:1100}}>
                    <img src="/images/loading.gif" width={40} height={40}/>
                </div>
            );
        }
    }


    showContent(){

        const {visible} = this.props;

        if(visible){
            return (
                <div>
                    <div className="sign-in-box model fadeInUp animated">
                        <div style={{position:'absolute', top:'5px', right:'5px'}}>
                            <a href="javascript:void(0)" onClick={()=>this.hideDiv()}><img src="/images/close.png" width={20} height={20}/></a>
                        </div>
                        <div className="sigin-left">
                            <div className="signin-form clearfix">
                                {this.showLoading()}
                                <h4 className="social-signin-heading">账号注册</h4>
                                <form>
                                    <div className="signin-section clearfix">
                                        <input ref="username" className="form-input form-input-first" name="username" placeholder="邮箱(找回密码用)" type="text"
                                               onBlur={this.validateEmail}
                                        />

                                        <input ref="password" className="form-input" placeholder="密码(4-32位)" name="password"
                                               onBlur={this.validatePassword}
                                        />

                                        <input ref="nickname" className="form-input" name="nickname" placeholder="昵称(英文1-14位,中文1-7位)" type="text"
                                               onBlur={this.validateNickname}
                                        />
                                    </div>
                                    <div class="signin-error" id="signin-error">{this.state.errorInfo}</div>
                                    <button type="button"  onClick={()=>this.handleSubmit()} className="form-submit">注册</button>
                                </form>
                            </div>
                            <div className="signin-foot clearfix">
                            </div>
                        </div>
                    </div>
                    <div className="shade" style={this.state.loading ? {zIndex:1501} : {}} onClick={()=>this.hideDiv()}></div>
                </div>
            );
        }else{
            return (<div></div>);
        }
    }

    render(){
        return (
            <div>
                {this.showContent()}
            </div>
        );
    }

}

export default RegisterForm;
